/*
 * Copyright (c) 2008-2021 浩瀚深度 All Rights Reserved.
 *
 * <p>FileName: WeChatController.java</p>
 *
 * @author zz
 * @date 2024/4/12
 * @version 1.0
 * History:
 * v1.0.0 2024/4/12 Create
 */
package com.haohan.mess.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.haohan.mess.api.WeiXinApi;
import com.haohan.mess.base.Result;
import com.haohan.mess.base.ResultCode;
import com.haohan.mess.entity.ArticleDb;
import com.haohan.mess.entity.WxSearchReq;
import com.haohan.mess.mapper.ArticleMapper;
import com.haohan.mess.model.Article;
import com.haohan.mess.model.BizData;
import com.haohan.mess.model.WxResultBody;
import com.haohan.mess.okhttp.MyCookieStore;
import com.haohan.mess.service.WeChatService;
import com.haohan.mess.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: WeChatController</p>
 * <p>Description: </p>
 *
 * @author zz
 */
@Slf4j
@RestController
@RequestMapping("/chat")
@CrossOrigin(origins = "*")
public class WeChatController {
    @Autowired
    private WeChatService weChatService;

    @Autowired
    private ArticleMapper articleMapper;

    @GetMapping("/qr-code")
    public ResponseEntity<byte[]> getQRCode() {
        log.info("获取登录二维码");
        // 1. POST请求开始登录接口，初始化cookie
        String sessionid = "" + System.currentTimeMillis() + (int) (Math.random() * 100);
        WxResultBody wxResultBody = WeiXinApi.startLogin(sessionid);
        log.info("---请求开始登录接口 返回结果:" + wxResultBody.toString());

        try (
                InputStream qrCodeIs = WeiXinApi.getQRCode();
                ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {

            int nRead;
            byte[] data = new byte[1024];
            while ((nRead = qrCodeIs.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            // 确保所有数据都被写入
            buffer.flush();

            // 返回响应实体
            return ResponseEntity
                    .ok()
                    .contentType(MediaType.IMAGE_PNG)
                    .body(buffer.toByteArray());
        } catch (IOException e) {
            return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(null);
        }
    }


    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getQRCodeStatus() {
        log.info("获取登录状态");
        Map<String, Object> response = new HashMap<>();
        int status = weChatService.getQRCodeStatus();
        switch (status) {
            case 0:
                response.put("message", "请扫描二维码");
                response.put("status", 0);
                break;
            case 4:
                response.put("message", "已扫码，请确认");
                response.put("status", 4);
                break;
            case 2:
                // 可能更多的状态处理
                break;
            case 3:
                response.put("message", "二维码已过期");
                response.put("status", 3);
                break;
            case 1:
                response.put("message", "登录成功");
                response.put("status", 1);
                getLoginToken();
                break;
            default:
                response.put("message", "未知状态");
                response.put("status", -1);
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
        return ResponseEntity.ok(response);
    }


    private String getLoginToken() {
        // 4.确认登录后，请求登录接口，拿到登录状态的cookie
        WxResultBody bizlogin = WeiXinApi.bizlogin();
        //重定向地址
        String redirect_url = bizlogin.getRedirect_url();
        //解析成键值对
        Map<String, String> loginRes = HttpUtils.parseQueryParams(redirect_url);
        //得到token
        String token = loginRes.get("token");
        log.info("当前登录token:" + token);
        //设置全局token值
        MyCookieStore.setToken(token);
        return token;
    }

    @PostMapping("/searchAuthor")
    public Result searchAuthor(@RequestBody WxSearchReq req) {
        List<BizData> list = null;
        try {
            WxResultBody<List<BizData>> searchBiz = WeiXinApi.searchBiz(req.getName());
            list = searchBiz.getList();
        } catch (Exception e) {
            log.error("检索失败:" + e);
        }
        return new Result(ResultCode.SUCCESS, list);
    }

    @PostMapping("/searchArticle")
    public Result searchArticle(@RequestBody WxSearchReq req) {
        log.info("检索文章入参:" + JSON.toJSONString(req));
        List<Article> list = null;
        try {
            WxResultBody<List<Article>> searchBiz = WeiXinApi.findExList(req.getId());
            list = searchBiz.getApp_msg_list();
            log.info("检索文章结果:" + JSON.toJSONString(list));
            if(CollectionUtil.isNotEmpty(list)){
                list.stream().forEach(data->{
                    ArticleDb articleDb = new ArticleDb();
                    articleDb.setCover(data.getCover());
                    articleDb.setLink(data.getLink());
                    articleDb.setFakeId(req.getId());
                    articleDb.setTitle(data.getTitle());
                    articleMapper.insert(articleDb);
                });
            }
        } catch (Exception e) {
            log.error("检索文章失败:" + e);
        }
        return new Result(ResultCode.SUCCESS, list);
    }

}
